package audio

import (
	"os"
	"testing"
)

func getFileSize(filePath string) (int64, error) {
	fileInfo, err := os.Stat(filePath)
	if err != nil {
		return 0, err
	}
	return fileInfo.Size(), nil
}

func Test_Conv_Wav(t *testing.T) {
	pcmPath := "../test_data/nihao.pcm"
	wavPath := "../test_data/nihao.wav"
	err := ConvertPCMToWAV(pcmPath, wavPath, 44100, 1)
	if err != nil {
		t.Error(err)
	} else {
		t.Log("Test_Conv_Wav success")

		// 打开并检查WAV文件头部信息
		wav, err := os.Open(wavPath)
		if err != nil {
			t.Fatalf("Failed to open WAV file: %v", err)
		}
		defer wav.Close()

		// check wav header
		wavHeader := make([]byte, wavHeaderSize)
		_, err = wav.Read(wavHeader)
		if err != nil {
			t.Fatalf("Failed to read WAV header: %v", err)
		}

		// 检查 RIFF 标识
		if string(wavHeader[0:4]) != "RIFF" {
			t.Errorf("Invalid RIFF header: got %s", wavHeader[0:4])
		}

		// 检查 WAVE 标识
		if string(wavHeader[8:12]) != "WAVE" {
			t.Errorf("Invalid WAVE format: got %s", wavHeader[8:12])
		}

		// 检查 PCM 数据长度是否正确
		pcmSize, fErr := getFileSize(pcmPath)
		if fErr != nil {
			t.Errorf("Failed to get file size: %v", fErr)
		}
		expectedDataSize := int(pcmSize)
		actualDataSize := int(wavHeader[40]) | int(wavHeader[41])<<8 | int(wavHeader[42])<<16 | int(wavHeader[43])<<24
		if actualDataSize != expectedDataSize {
			t.Errorf("Incorrect data size: got %d, expected %d", actualDataSize, expectedDataSize)
		}
	}
}
